package com.zhuliwei.service.impl;

import com.zhuliwei.constants.SystemConstants;
import com.zhuliwei.domain.ResponseResult;
import com.zhuliwei.domain.entity.LoginUser;
import com.zhuliwei.domain.entity.User;
import com.zhuliwei.service.AdminAuthService;
import com.zhuliwei.service.UserService;
import com.zhuliwei.utils.IPUtil;
import com.zhuliwei.utils.JwtUtil;
import com.zhuliwei.utils.RedisCache;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Objects;

/**
 * 后台认证接口实现类
 *
 * @author 朱力维
 * @time 2022/10/25 15:36
 **/
@Service
public class AdminAuthServiceImpl implements AdminAuthService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Resource
    private UserService userService;

    @Resource
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user, HttpServletRequest request) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        // 认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 判断认证是否通过
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //获取userid 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();//获取用户实体
        String userId = loginUser.getUser().getId();
        String jwt = JwtUtil.createJWT(userId);
        //把用户信息存入redis
        redisCache.setCacheObject(SystemConstants.ADMIN_LOGIN_PREFIX + userId, loginUser);
        // 记录登录后的IP地址
        String ipAddress = IPUtil.getIpAddress(request);
        User user1 = loginUser.getUser();
        user1.setIpaddress(ipAddress);
        // 记录登录时间
        user1.setLogintime(new Date());
        userService.updateById(user1);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult logout() {
        //获取userId
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUser().getId();
        //删除Redis中的用户信息
        redisCache.deleteObject(SystemConstants.ADMIN_LOGIN_PREFIX + userId);
        return ResponseResult.okResult();
    }
}
